package com.softstao.guoyu.ui.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.igexin.sdk.PushManager;
import com.softstao.guoyu.R;
import com.softstao.guoyu.accept.Accept;
import com.softstao.guoyu.base.BaseFragment;
import com.softstao.guoyu.global.APIInterface;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.global.UserManager;
import com.softstao.guoyu.model.me.Icon;
import com.softstao.guoyu.model.me.PersonalInfo;
import com.softstao.guoyu.model.me.User;
import com.softstao.guoyu.model.sale.ToOrder;
import com.softstao.guoyu.mvp.events.NotifyEvent;
import com.softstao.guoyu.mvp.interactor.me.UserInfoInteractor;
import com.softstao.guoyu.mvp.presenter.me.UserInfoPresenter;
import com.softstao.guoyu.mvp.viewer.me.UserInfoViewer;
import com.softstao.guoyu.ui.activity.LoginActivity;
import com.softstao.guoyu.ui.activity.MainActivity;
import com.softstao.guoyu.ui.activity.WebViewActivity;
import com.softstao.guoyu.ui.activity.agent.AboutOrderActivity;
import com.softstao.guoyu.ui.activity.agent.AuditListActivity;
import com.softstao.guoyu.ui.activity.agent.InviteActivity;
import com.softstao.guoyu.ui.activity.me.BalanceActivity;
import com.softstao.guoyu.ui.activity.me.MessageActivity;
import com.softstao.guoyu.ui.activity.me.MyAuditActivity;
import com.softstao.guoyu.ui.activity.me.RebateActivity;
import com.softstao.guoyu.ui.activity.me.UserInfoActivity;
import com.softstao.guoyu.ui.activity.sale.MyOrderListActivity;
import com.softstao.guoyu.ui.activity.sale.SaleRebateActivity;
import com.softstao.guoyu.ui.adapter.MeIconAdapter;
import com.softstao.guoyu.widget.HintDialog;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.BadgeView.BadgeView;
import com.softstao.softstaolibrary.library.widget.CircleImageView;
import com.softstao.softstaolibrary.library.widget.CustomGridView;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/7.
 */

public class MeFragment extends BaseFragment implements UserInfoViewer {

    @AIPresenter(presenter = UserInfoPresenter.class, interactor = UserInfoInteractor.class)
    UserInfoPresenter presenter;

    @BindView(R.id.avatar)
    CircleImageView avatar;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.mobile)
    TextView mobile;
    @BindView(R.id.balance)
    TextView balance;
    @BindView(R.id.grade)
    TextView grade;
    @BindView(R.id.icon_view)
    CustomGridView iconView;
    @BindView(R.id.order1)
    LinearLayout order1;
    @BindView(R.id.order2)
    LinearLayout order2;
    @BindView(R.id.order3)
    LinearLayout order3;
    @BindView(R.id.order4)
    LinearLayout order4;
    @BindView(R.id.order5)
    LinearLayout order5;
    @BindView(R.id.version)
    TextView version;
    private MeIconAdapter meIconAdapter;
    private List<Icon> iconList = new ArrayList<>();
    private User user;
    private String level_name;
    private int[] imgList = {R.mipmap.me_icon_yeji, R.mipmap.me_icon_fanli, R.mipmap.me_icon_shouquan,
            R.mipmap.me_icon_jingxiaoshang, R.mipmap.me_icon_shenhe, R.mipmap.me_icon_xunibi,
            R.mipmap.me_icon_wenti, R.mipmap.me_icon_kefu, R.mipmap.me_icon_gonggao, R.mipmap.me_icon_balance};
    private String[] nameList = {"我的业绩", "我的返利", "我的授权", "邀请经销商", "授权审核", "虚拟币",
            "常见问题", "客服", "公司公告", "我的收入"};
    private BadgeView msgBadge, dot1, dot2, dot3, dot4, dot5;

    @Override
    public int _ContentView() {
        return R.layout.fragment_me;
    }

    @Override
    public void initView() {
        setTitleBar("我的");
        titleBar.setRightIcon(R.mipmap.title_btn_news);
        titleBar.setRightIconOnClick(v -> startActivity(new Intent(mContext, MessageActivity.class)));

        addIcon();
        meIconAdapter = new MeIconAdapter(iconList);
        iconView.setAdapter(meIconAdapter);
        iconView.setOnItemClickListener((parent, view, position, id) ->
                Goto(iconList.get(position).getPic())
        );

        msgBadge = new BadgeView(mContext);
        dot1 = new BadgeView(mContext);
        dot2 = new BadgeView(mContext);
        dot3 = new BadgeView(mContext);
        dot4 = new BadgeView(mContext);
        dot5 = new BadgeView(mContext);

        try {
            version.setText("当前版本：" + mContext.getPackageManager().getPackageInfo(mContext.getPackageName(),0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void initData() {
        if (user != null) {
            if (user.getAvatar() != null && !user.getAvatar().equals("")) {
                Glide.with(mContext).load(user.getAvatar()).apply(new RequestOptions().centerCrop()).into(avatar);
            } else {
                avatar.setImageResource(R.mipmap.default_avatar);
            }
            name.setText(user.getName());
            mobile.setText(user.getMobile());
            balance.setText("虚拟币：" + LZUtils.priceFormat(user.getBalance()) + "元");
            switch (User.Type.fromInteger(user.getLevel())) {
                case ANGEL:
                    level_name = "天使";
                    break;
                case CROWN:
                    level_name = "皇冠";
                    break;
                case ONE_LEVEL:
                    level_name = "一级";
                    break;
                case CITY_LEVEL:
                    level_name = "市级";
                    break;
                case PROVINCE:
                    level_name = "省代";
                    break;
                case HEADQUARTER:
                    level_name = "总部";
                    break;
                case UNAGENT:
                    level_name = "未授权";
                    break;
            }
            grade.setText("等级：" + level_name);

            if (SharePreferenceManager.getInstance().getLogin() == true) {
                if (SharePreferenceManager.getInstance().getDirectlyList().getIsCompleteInfo() == 0) {
                    showLogin();
                }
            }
        } else {
            avatar.setImageResource(R.mipmap.default_avatar);
            balance.setText("虚拟币：0");
            grade.setText("等级：无");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        findUserInfo();
    }

    private void addIcon() {
        for (int i = 0; i < imgList.length; i++) {
            if (i!=9) {
                Icon icon = new Icon();
                icon.setPic(imgList[i]);
                icon.setName(nameList[i]);
                iconList.add(icon);
            }
        }
    }

    private void Goto(int position) {
        switch (position) {
            case R.mipmap.me_icon_yeji:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, AboutOrderActivity.class).putExtra("type", "user"));
                break;
            case R.mipmap.me_icon_fanli:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, RebateActivity.class));
                break;
            case R.mipmap.me_icon_shouquan:
                if (SharePreferenceManager.getInstance().getDirectlyList().getIsCompleteInfo() == 0) {
                    ((MainActivity) getActivity()).showInfo();
                    return;
                }
                startActivity(new Intent(mContext, MyAuditActivity.class));
                break;
            case R.mipmap.me_icon_jingxiaoshang:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, InviteActivity.class));
                break;
            case R.mipmap.me_icon_shenhe:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, AuditListActivity.class));
                break;
            case R.mipmap.me_icon_xunibi:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, BalanceActivity.class));
                break;
            case R.mipmap.me_icon_wenti:
                Intent askIntent = new Intent(mContext, WebViewActivity.class);
                askIntent.putExtra("title", "常见问题");
                askIntent.putExtra("url", APIInterface.SERVER_WAP + "issue.html");
                startActivity(askIntent);
                break;
            case R.mipmap.me_icon_kefu:
                Intent kefuIntent = new Intent(mContext, WebViewActivity.class);
                kefuIntent.putExtra("title", "客服");
                kefuIntent.putExtra("url", APIInterface.SERVER_WAP + "kefu.html");
                startActivity(kefuIntent);
                break;
            case R.mipmap.me_icon_gonggao:
                Intent noticeIntent = new Intent(mContext, WebViewActivity.class);
                noticeIntent.putExtra("title", "公司公告");
                noticeIntent.putExtra("url", APIInterface.SERVER_WAP + "companyNotice.html");
                startActivity(noticeIntent);
                break;
            case R.mipmap.me_icon_balance:
                startActivity(new Intent(mContext, SaleRebateActivity.class));
                break;
        }
    }

    @OnClick({R.id.avatar, R.id.info, R.id.all_order, R.id.order1, R.id.order2, R.id.order3,
            R.id.order4, R.id.order5})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.avatar:
            case R.id.info:
                startActivity(new Intent(mContext, UserInfoActivity.class));
                break;
            case R.id.all_order:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, MyOrderListActivity.class).putExtra("orderState", ""));
                break;
            case R.id.order1:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, MyOrderListActivity.class).putExtra("orderState", ToOrder.UNCONFIRM + ""));
                break;
            case R.id.order2:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, MyOrderListActivity.class).putExtra("orderState", ToOrder.UNPAY + ""));
                break;
            case R.id.order3:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, MyOrderListActivity.class).putExtra("orderState", ToOrder.PAYED + ""));
                break;
            case R.id.order4:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, MyOrderListActivity.class).putExtra("orderState", ToOrder.SHIPPED + ""));
                break;
            case R.id.order5:
                if (!((MainActivity) getActivity()).Complete()) {
                    return;
                }
                startActivity(new Intent(mContext, MyOrderListActivity.class).putExtra("orderState", ToOrder.CANCEL + ""));
                break;
        }
    }

    private void showLogin() {
        HintDialog dialog = new HintDialog(mContext, R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth() - LZUtils.dipToPix(mContext, 55) * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setIcon(R.mipmap.hint_icon_success);
        dialog.setTitle("登录成功");
        dialog.setContentVisible();
        dialog.setContent("请完善资料，尽早获得授权！");
        dialog.setConfirm("去完善资料");
        dialog.getConfirm().setOnClickListener(v -> {
            dialog.dismiss();
            SharePreferenceManager.getInstance().setLogin(false);
            startActivity(new Intent(mContext, UserInfoActivity.class));
        });
        dialog.getCancelIc().setOnClickListener(v -> {
            SharePreferenceManager.getInstance().setLogin(false);
            dialog.dismiss();
        });
        dialog.show();
    }

    @Override
    public void findUserInfo() {
        presenter.getUserInfo(SharePreferenceManager.getInstance().getAgentId());
    }

    @Override
    public void getUserInfo(PersonalInfo personalInfo) {
        if (personalInfo != null) {
            UserManager.getInstance().setUser(personalInfo.getPersonalInfo());
            user = UserManager.getInstance().getUser();
            initData();
            if (user.getState() == 4 || user.getState() == 7) {
                LZToast.getInstance(mContext).showToast("您已被退/禁用，强制下线");
                CookieSyncManager.createInstance(mContext);
                CookieManager.getInstance().removeAllCookie();
                SharePreferenceManager.getInstance().setCookie("");
                UserManager.getInstance().setUser(null);
                PushManager.getInstance().unBindAlias(mContext, String.valueOf(SharePreferenceManager.getInstance().getAgentId()), true);
                SharePreferenceManager.getInstance().setAgentId(0);
                SharePreferenceManager.getInstance().setLoginInfo(null);
                startActivity(new Intent(mContext, LoginActivity.class));
            }
        }
    }

    @Accept
    public void notifyEvent(Object tag, NotifyEvent event) {
        if (event.getNotify() != 0) {
            msgBadge.setVisibility(View.VISIBLE);
            msgBadge.setTargetView(titleBar.getRightImageView());
            msgBadge.setBadgeMargin(0, 5, 0, 0);
            msgBadge.setTextSize(1);
            msgBadge.setText(" ");
            msgBadge.setHideOnNull(true);
            msgBadge.setmShowNumber(true);
            int padding = LZUtils.dipToPix(mContext, 2);
            int padding1 = LZUtils.dipToPix(mContext, 3);
            msgBadge.setPadding(padding1, padding, padding1, padding);
        } else {
            msgBadge.setVisibility(View.GONE);
        }
        int padding1 = LZUtils.dipToPix(getContext(), 4);
        int padding2 = LZUtils.dipToPix(getContext(), 1);
        if (event.getTransferOrderCount().get(0) != 0) {
            dot1.setVisibility(View.VISIBLE);
            dot1.setTargetView(order1);
            dot1.setBadgeMargin(0, 3, 10, 0);
            dot1.setPadding(padding1, padding2, padding1, padding2);
            dot1.setTextColor(getResources().getColor(R.color.white));
            dot1.setTextSize(8);
            dot1.setHideOnNull(true);
            dot1.setBadgeCount(event.getTransferOrderCount().get(0));
        } else {
            dot1.setVisibility(View.GONE);
        }
        if (event.getTransferOrderCount().get(1) != 0) {
            dot2.setVisibility(View.VISIBLE);
            dot2.setTargetView(order2);
            dot2.setBadgeMargin(0, 3, 10, 0);
            dot2.setPadding(padding1, padding2, padding1, padding2);
            dot2.setTextColor(getResources().getColor(R.color.white));
            dot2.setTextSize(8);
            dot2.setHideOnNull(true);
            dot2.setBadgeCount(event.getTransferOrderCount().get(1));
        } else {
            dot2.setVisibility(View.GONE);
        }
        if (event.getTransferOrderCount().get(2) != 0) {
            dot3.setVisibility(View.VISIBLE);
            dot3.setTargetView(order3);
            dot3.setBadgeMargin(0, 3, 10, 0);
            dot3.setPadding(padding1, padding2, padding1, padding2);
            dot3.setTextColor(getResources().getColor(R.color.white));
            dot3.setTextSize(8);
            dot3.setHideOnNull(true);
            dot3.setBadgeCount(event.getTransferOrderCount().get(2));
        } else {
            dot3.setVisibility(View.GONE);
        }
        if (event.getTransferOrderCount().get(3) != 0) {
            dot4.setVisibility(View.VISIBLE);
            dot4.setTargetView(order4);
            dot4.setBadgeMargin(0, 3, 10, 0);
            dot4.setPadding(padding1, padding2, padding1, padding2);
            dot4.setTextColor(getResources().getColor(R.color.white));
            dot4.setTextSize(8);
            dot4.setHideOnNull(true);
            dot4.setBadgeCount(event.getTransferOrderCount().get(3));
        } else {
            dot4.setVisibility(View.GONE);
        }
        if (event.getTransferOrderCount().get(4) != 0) {
            dot5.setVisibility(View.VISIBLE);
            dot5.setTargetView(order5);
            dot5.setBadgeMargin(0, 3, 10, 0);
            dot5.setPadding(padding1, padding2, padding1, padding2);
            dot5.setTextColor(getResources().getColor(R.color.white));
            dot5.setTextSize(8);
            dot5.setHideOnNull(true);
            dot5.setBadgeCount(event.getTransferOrderCount().get(4));
        } else {
            dot5.setVisibility(View.GONE);
        }
    }
}
